from langchain.output_parsers import OutputFixingParser
from langchain_core.output_parsers import PydanticOutputParser
from langchain_openai import ChatOpenAI
from pydantic import BaseModel, Field
from typing import List

class Actor(BaseModel):
    name: str = Field(description="演员姓名")
    film_names: List[str] = Field(description="参演电影列表")

parser = PydanticOutputParser(pydantic_object=Actor)

# 定义模型
model = ChatOpenAI(
    model_name = "qwen-plus",
    base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
    api_key="sk-005c3c25f6d042848b29d75f2f020f08",
    temperature=0.7
)

# 包装原始解析器
fixing_parser = OutputFixingParser.from_llm(parser=parser, llm=model,max_retries=5)

# 模拟模型输出的错误格式（使用单引号）
misformatted_output = "{'name': '小滴课堂老王', 'film_names': ['A计划','架构大课','一路向西']}"

# try:
#     parsed_data = parser.parse(misformatted_output)  # 直接解析会失败
# except Exception as e:
#     print(f"解析失败: {e}")  # 抛出JSONDecodeError

# 使用OutputFixingParser修复并解析
fixed_data = fixing_parser.parse(misformatted_output)

print(type(fixed_data))
print(fixed_data.model_dump())
# 输出: {'name': '小滴课堂老王', 'film_names': ['A计划', '架构大课', '一路向西']}